package com.wanmait.wanmarecruit.manageController;

import com.wanmait.wanmarecruit.entity.Manager;
import com.wanmait.wanmarecruit.enumeration.ErrorEnum;
import com.wanmait.wanmarecruit.service.ManagerService;
import com.wanmait.wanmarecruit.util.AjaxResult;
import com.wanmait.wanmarecruit.util.JWTUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("manage")
public class ManageLoginController {
    @Resource
    private ManagerService managerService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("errorToken")
    public void errorToken(HttpServletRequest request)
    {
        AuthenticationException exception = (AuthenticationException) request.getAttribute("exception");
        throw exception;
    }

    @PostMapping("tryLogin")
    public AjaxResult tryLogin(@RequestBody Manager manager)
    {
        Manager loginManager = managerService.checkNameAndPass(manager);
        if (loginManager==null) {
            return AjaxResult.error(ErrorEnum.LOGIN_FAILED.getCode(),ErrorEnum.LOGIN_FAILED.getInfo());
        }
        Map<String,String> chain = new HashMap<>();
        chain.put("name",loginManager.getName());
        String token = JWTUtils.createToken(loginManager.getId()+"",60,loginManager.getPass(),chain);
        redisTemplate.opsForValue().set(token,loginManager,60,TimeUnit.MINUTES);
        loginManager.setPass("");
        managerService.updateLoginTime(loginManager.getId());
        return AjaxResult.success("登录成功").put("loginManager",loginManager).put("token",token);
    }
    @GetMapping("list")
    public AjaxResult list()
    {
        return AjaxResult.success("成功了");
    }


    @RequestMapping("/code")
    public AjaxResult createCode(HttpServletRequest request) throws IOException {
        int width = 90,height=30;
        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,width,height);
        char[] arr = {'A', 'B', 'C', 'D', 'E','F','G','H','J','K','M','N','P','Q','R','S','T','U','V', 'W','X','Y','Z',
                'a','b','c','d','e','f','g','h','j','k','l','m','n', 'p','q','r','s','t','u','v','w','x','y','z',
                '0', '1', '2', '3', '4', '5', '6','7','8','9'};
        String code="";
        for (int i=0;i<4;i++)
        {
            int index = random.nextInt(arr.length);
            char c = arr[index];
            code = code+c;
            graphics.setColor(createRandomColor());
            graphics.setFont(new Font(Font.DIALOG,Font.BOLD+Font.ITALIC,19));
            graphics.drawString(String.valueOf(c),10+(i*20),20);
        }
        //干扰线
        for (int i = 0; i <10; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphics.setColor(createRandomColor());
            graphics.drawLine(x1,y1,x2,y2);
        }

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage,"jpg",stream);
        byte[] bytes = stream.toByteArray();

        Base64.Encoder encoder = Base64.getEncoder();
        String base64 = encoder.encodeToString(bytes).trim();
        base64 = base64.replaceAll("\n","").replaceAll("\r","");
        String codeKey = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(codeKey,code,5, TimeUnit.MINUTES);
        return AjaxResult.success().put("codeImg","data:image/jpg;base64,"+base64).put("codeKey",codeKey);
    }

    private Random random = new Random();

    private Color createRandomColor()
    {
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue=random.nextInt(256);
        return new Color(red,green,blue);
    }

    @GetMapping("checkCode")
    public AjaxResult checkCode(String code,String codeKey)
    {
        String rightCode = (String)redisTemplate.opsForValue().get(codeKey);
        if (rightCode==null)
        {
            return AjaxResult.error(ErrorEnum.CODE_INVALID.getCode(),ErrorEnum.CODE_INVALID.getInfo());
        }
        if (rightCode.equalsIgnoreCase(code))
        {
            return AjaxResult.success("验证码正确");
        }
        return AjaxResult.error(ErrorEnum.CODE_ERROR.getCode(),ErrorEnum.CODE_ERROR.getInfo());
    }
}
